import React from 'react';
import { makeStyles, withStyles } from '@material-ui/core/styles';
import { Typography, Grid, Button, TextField } from '@material-ui/core';
import validate from 'validate.js';
import { LearnMoreLink } from 'components/atoms';
import MuiPhoneNumber from 'material-ui-phone-number';
import { useSelector, useDispatch } from 'react-redux'
import ReactHtmlParser from 'react-html-parser';
import { setLoading } from 'redux/actions/LoadingActions';
import { useHistory, useLocation } from "react-router-dom";
import { callPostApi } from 'utils/networking';

const useStyles = makeStyles(theme => ({
  root: {
    width: '100%',
  },
  numberField: {
    width: '100%',
  }
}));

const schema = {
  code: {
    presence: { allowEmpty: false, message: 'is required' },
    length: {
      maximum: 4,
    },
  },
  number: {
    presence: { allowEmpty: false, message: 'is required' },
    length: {
      maximum: 20,
    },
  }
};

const RedTextTypography = withStyles({
  root: {
    color: "#FF0000",
    marginBottom: '20px'
  }
})(Typography);

const Form = () => {
  const classes = useStyles();
  const dispatch = useDispatch();
  let history = useHistory();
  let location = useLocation();

  const preAuthPath = useSelector((state) => state.auth.preAuthPath);
  const profileData = useSelector((state) => state.auth.profileData);

  const [verifyCode, setCode] = React.useState('');
  const [callbackError, setCallbackError] = React.useState('');

  const [formState, setFormState] = React.useState({
    isValid: false,
    values: {},
    touched: {},
    errors: {},
  });

  React.useEffect(() => {
    const errors = validate(formState.values, schema);

    setFormState(formState => ({
      ...formState,
      isValid: errors ? false : true,
      errors: errors || {},
    }));
  }, [formState.values]);

  const handleChange = event => {
    event.persist();
    setCallbackError('');
    
    setFormState(formState => ({
      ...formState,
      values: {
        ...formState.values,
        [event.target.name]:
          event.target.type === 'checkbox'
            ? event.target.checked
            : event.target.value,
      },
      touched: {
        ...formState.touched,
        [event.target.name]: true,
      },
    }));
  };

  const handleNumberChange = (value) => {
    setCallbackError('');
    setCode('')

    setFormState(formState => ({
      ...formState,
      values: {
        ...formState.values,
        number: value,
      },
      touched: {
        ...formState.touched,
        number: true,
      },
    }));
  }

  const handleSubmit = async event => {
    event.preventDefault();

    if (verifyCode) {
      if (formState.isValid) {
        await updateProfile();
      }

      if (verifyCode != formState.values.code) {
        setCallbackError('Invalid code');
        return
      }

      setFormState(formState => ({
        ...formState,
        touched: {
          ...formState.touched,
          ...formState.errors,
        },
      }));

    } else {
      if (formState.values.number) {
        await sendCode()

      } else {
        setCallbackError('Input phone number')
      }
    }
  };

  const hasError = field =>
    formState.touched[field] && formState.errors[field] ? true : false;

  const sendCode = async () => {
    callPostApi('user/send_verify_code', { phone: formState.values.number }, dispatch, (data) => {
      dispatch(setLoading(false))
      console.log(data)
      setCode(data)
    })
  }

  const updateProfile = async () => {
    callPostApi('user/update_phone', { user_id: profileData.id, phone: formState.values.number }, dispatch, (data) => {
      dispatch(setLoading(false))
      if (preAuthPath) {
        history.replace(preAuthPath);
      } 
      else {
        history.replace("");
      }
    })
  }

  return (
    <div className={classes.root}>
      <form name="password-reset-form" method="post" onSubmit={handleSubmit}>
        <Grid container spacing={2}>
          {callbackError && (
            <Grid item xs={12}>
              <RedTextTypography
                align="center"
                className={classes.errorLabel}
              >
                {ReactHtmlParser(callbackError)}
              </RedTextTypography>
            </Grid>
          )}
          <Grid item xs={12}>
            <MuiPhoneNumber
              defaultCountry={'us'}
              onChange={handleNumberChange}
              className={classes.numberField}
              name="number"
              helperText={hasError('number') ? formState.errors.number[0] : null}
              error={hasError('number')} />
          </Grid>
          {verifyCode && (
            <Grid item xs={12}>
              <TextField
                placeholder="Please enter verification code"
                label="Verify code *"
                variant="outlined"
                size="medium"
                name="code"
                fullWidth
                type="text"
                onChange={handleChange}
                helperText={hasError('code') ? formState.errors.code[0] : null}
                error={hasError('code')
              }
              />
            </Grid>
          )}
          <Grid item xs={12}>
            <Button
              size="large"
              variant="contained"
              type="submit"
              color="primary"
              fullWidth
            >
              {verifyCode ? "Verify" : "Send Code"}
            </Button>
          </Grid>
          <Grid item xs={12}>
            <Typography
              variant="subtitle1"
              color="textSecondary"
              align="center"
            >
              Didn't you receive? &nbsp;&nbsp;
              <LearnMoreLink title="Send Code" onClick={sendCode} />
            </Typography>
          </Grid>
        </Grid>
      </form>
    </div>
  );
};

export default Form;
